/**  
* @Title: SessionServiceImpl.java
* @Package cn.com.gzheroli.bfw.service.impl  
* @Description: TODO(用一句话描述该文件做什么)  
* @author 李长荣  
* @date 2016年12月29日  
* @version V1.0  
*/
package cn.com.gzheroli.bfw.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Service;

import cn.com.gzheroli.bfw.bean.LockInfo;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.bfw.service.SessionService;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.manager.Client;

/**  
* @ClassName:SessionServiceImpl 
* @Description: 会话管理  
* @author 李长荣  
* @date 2016年12月29日  
*/
@Service("sessionService")
public class SessionServiceImpl implements SessionService{
	
	private static Integer lockType=Calendar.MINUTE;
	private static Integer lockNum=60;
	@Autowired
	private RedisOperationsSessionRepository sessionRepository;
	@Autowired
    private SpringRedisCache cache;
    /** 
     * 移除用户Session 
     */  
    public synchronized  void removeUserSession(String token) {  
    	cache.deleteCache(token);
    	sessionRepository.delete(token);
		sessionRepository.cleanupExpiredSessions();
    }  
   

  
    /** 
     * 判断该用户是否已重复登录，使用 
     * 同步方法，只允许一个线程进入，才好验证是否重复登录 
     * @param user 
     * @return 
     */  
    	public synchronized  boolean checkIfHasLogin(String token,String userId,String loginMethod) {
             Client client =cache.getCache(token, Client.class);
             if(null!=client){
            	 TSUser sessionuser =client.getUser();// 这是你设置 保存用户对应session名
                 if (sessionuser != null) {
                     if (sessionuser.getId()!=null&&sessionuser.getId().equals(userId)&&client.getLoginMethod()!=null&&client.getLoginMethod().equals(loginMethod)){
                         return true;
                     }
                 }
             }
    		return false;
    	}
    	

    	/**
    	 * 检查是否 被锁 ,若超过锁定时间 视为解锁
    	 * @param userid
    	 * @return
    	 */
    	public synchronized Boolean isLockUser(String username){
    		Map lockUsers=cache.getCache("lockUsers", HashMap.class);
    		if(null==lockUsers||!lockUsers.containsKey(username))
    			return false;
    		LockInfo lockInfo=(LockInfo)lockUsers.get(username);
    		Long lockTime= lockInfo.getLockTime();
    		if(null==lockTime){
    			return false;		
    		}	
    		if(new Date().getTime()>=lockTime)
    		{
    			lockUsers.remove(username);
    			cache.deleteCache("lockUsers");
    			cache.putCache("lockUsers", lockUsers);
    			return false;
    		}		
    		return true;
    	}
    	
    	/**
    	 * 累计输入失败数量
    	 * @param userid
    	 */
    	public synchronized void addCount(String username){
    		Map lockUsers=cache.getCache("lockUsers", HashMap.class);
    		if(lockUsers==null||!lockUsers.containsKey(username)){
    			if(lockUsers==null)
    				lockUsers=new HashMap();
    			LockInfo info=new LockInfo();
    			info.setLockCount(1);
    			info.setUpdateTime(new Date());
    			info.setLockTime(null);
    			lockUsers.put(username, info);
    			if(cache.getCache("lockUsers", HashMap.class)==null)
    				cache.putCache("lockUsers", lockUsers);
    		}else {
    			LockInfo lockInfo=(LockInfo)lockUsers.get(username);
    			Integer  num=lockInfo.getLockCount();
    			Calendar calendar1=Calendar.getInstance();
    			calendar1.setTime(lockInfo.getUpdateTime());
//    			calendar1.add(Calendar.HOUR_OF_DAY, 2);
    			calendar1.add(lockType, lockNum);
    			if(calendar1.getTime().getTime()<new Date().getTime())
    			{
    				lockInfo.setLockCount(1);
    				lockInfo.setUpdateTime(new Date());
    			}else if(num+1==3){
    				lockInfo.setLockCount(0);
    				Calendar calendar2=Calendar.getInstance();
//    				calendar2.add(Calendar.HOUR_OF_DAY, 2);
    				calendar2.add(lockType, lockNum);
    				Long H2_long=calendar2.getTime().getTime();
    				lockInfo.setLockTime( H2_long);
    				lockInfo.setUpdateTime(new Date());
    			}else {
    				lockInfo.setLockCount(num+1);
    				lockInfo.setUpdateTime(new Date());
    			}			
    		}
    		cache.deleteCache("lockUsers");
			cache.putCache("lockUsers", lockUsers);
    	}
    	
    	/**
    	 * 解锁
    	 * @param userid
    	 */
    	public synchronized void unlockUser(String userid){
    		Map lockUsers=cache.getCache("lockUsers", HashMap.class);
    		if(lockUsers!=null&&lockUsers.containsKey(userid))
    			lockUsers.remove(userid);
    		cache.deleteCache("lockUsers");
			cache.putCache("lockUsers", lockUsers);
    	}
    	/**
    	 * 登录时使用 --  检查是否重复登录并把在线的 替换成 自己
    	 */
    	@Override
    	public void changeLogin4Me(Client client,String token,String clientType) {
    		String userId=client.getUser().getId();
    		String loginMethod=client.getLoginMethod();
    		Boolean hasLogin = checkIfHasLogin( token, userId, loginMethod); 
		    if(hasLogin)
			   removeUserSession(userId);
		    if(clientType==null||clientType.trim().equals("pc")||clientType.trim().equals(""))
		    	cache.putCacheWithExpireTime(token, client,30*60);
		    else if(clientType.trim().equals("app")){
		    	cache.putCacheWithExpireTime(token, client,30*24*60*60);
		    }else{
		    	cache.putCacheWithExpireTime(token, client,10*24*60*60);
		    }
		    	
    	}
}
